package xj.graph2d.encoder;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

import org.freehep.graphics2d.VectorGraphics;
import org.freehep.graphicsio.gif.GIFGraphics2D;

import xj.graph2d.DrawCanvas;
import xj.graph2d.View;

public class FreeHepGifEncoder extends FreeHepEncoder {

  public FreeHepGifEncoder() {
  }

  public FreeHepGifEncoder(String name, String fileExtension,
			   String fileDescription, View view) {
    super(name, fileExtension, fileDescription, GIF, view);
    imageTypeName = "gif";
  }

  @Override
  public void encode(String filename, Rectangle2D r) throws IOException {
    if (view != null) {
      DrawCanvas canvas = view.getCanvas();
      if (filename != null && 
	  imageTypeName != null && 
	  imageType == GIF && 
	  canvas != null && 
	  r != null) {
	int mw = (int) view.getMarginWidth();
	int mh = (int) view.getMarginHeight();
	int w = (int) r.getWidth() + 2 * mw;
	int h = (int) r.getHeight() + 2 * mw;

	BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
	Graphics2D g = (Graphics2D) image.getGraphics();
	setRenderingHints(g);

	if (!transparent) {
	  Color bg = view.getBackgroundColor();
	  g.setColor(bg);
	  g.fillRect(0, 0, w, h);
	}

	drawWaterMark(g, 0, 0, w, h);

	g.translate(-r.getX() + mw, -r.getY() + mh);
	view.paintCanvas(g, null, true); // draw all objects

	encodeImage(filename, image);
      }
    }
  }

  public void encodeImage(String filename, Image image) 
    throws IOException {
    if (image != null) {
      int width = image.getWidth(null);
      int height = image.getHeight(null);
      File file = new File(filename);
      Dimension dim = new Dimension(width, height);
      Properties p = new Properties();
      VectorGraphics g = null;
      if (imageType == GIF) {
	g = new GIFGraphics2D(file, dim);
      }
      if (g != null) {
	g.setProperties(p);
	g.startExport();
	g.drawImage(image, 0, 0, width, height, null);
	g.endExport();
      }
    }
  }

}
